/**
 * @file 书签管理器状态管理
 * @description 管理书签的本地增删改查、导入与云同步（本地明文存储）
 * 使用两表设计：文件夹层级 + 书签项
 */

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { createStorageState } from 'global-state'
import { BOOKMARK_MANAGER_CHANNELS } from '~shared/ipc-topic'

export interface BookmarkDTO extends F2.bookmark.BookmarkLocal {
  _id: string
}

export interface BookmarkFolderDTO extends F2.bookmark.BookmarkFolderLocal {
  _id: string
}

// Build hierarchical folder tree from database folders
export interface FolderNode {
  _id: string // null for unfiled bookmarks pseudo-folder
  name: string
  children: FolderNode[]
  bookmarks: BookmarkDTO[]
  hasChildren: boolean
  sort: number
  isUnfiled?: boolean // Mark the unfiled bookmarks node
}

interface QueryBookmarkParams {
  keyword?: string
  folder_id?: string | null
  page?: number
  pageSize?: number
  sortBy?: 'created_at' | 'updated_at' | 'title' | 'sort'
  sortOrder?: 'asc' | 'desc'
}

interface QueryFolderParams {
  parent_id?: string | null
  keyword?: string
  sortBy?: 'name' | 'created_at' | 'updated_at' | 'sort'
  sortOrder?: 'asc' | 'desc'
}

interface DatabaseResult<T = any> {
  success: boolean
  data?: T
  error?: string
  count?: number
}

interface BookmarkManagerSettings extends Record<string, unknown> {
  sync_enabled: boolean
  folderOrders: Record<string, string[]>
  expandedFolders: string[]
}

export const useBookmarkManagerStore = defineStore('bookmarkManager', () => {
  const items = ref<BookmarkDTO[]>([])
  const folders = ref<BookmarkFolderDTO[]>([])
  const isLoading = ref(false)
  const settings = createStorageState<BookmarkManagerSettings>(
    'bookmarkManagerSettings',
    {
      sync_enabled: true,
      folderOrders: {},
      expandedFolders: []
    },
    1
  )

  const total = ref(0)

  const hasBookmarks = computed(() => items.value.length > 0)

  async function invokeIPC<T = any>(channel: string, ...args: any[]): Promise<DatabaseResult<T>> {
    try {
      return await _pre_.ipcInvoke(channel, ...args)
    } catch (error) {
      console.error(`IPC 调用失败 (${channel}):`, error)
      return { success: false, error: error instanceof Error ? error.message : '操作失败' }
    }
  }

  // ==================== 文件夹操作 ====================

  async function addFolder(input: { name: string; parent_id?: string | null; sort?: number }) {
    const res = await invokeIPC<BookmarkFolderDTO>(BOOKMARK_MANAGER_CHANNELS.ADD_BOOKMARK, input)
    if (res.success) await loadFolders()
    return res
  }

  async function updateFolder(input: {
    _id: string
    name?: string
    parent_id?: string | null
    sort?: number
  }) {
    const res = await invokeIPC<BookmarkFolderDTO>(BOOKMARK_MANAGER_CHANNELS.UPDATE_FOLDER, input)
    if (res.success) await loadFolders()
    return res
  }

  async function deleteFolder(_id: string) {
    const res = await invokeIPC<boolean>(BOOKMARK_MANAGER_CHANNELS.DELETE_BOOKMARK, _id)
    if (res.success) {
      folders.value = folders.value.filter(f => f._id !== _id)
      await loadBookmarks() // 刷新书签列表
    }
    return res
  }

  async function loadFolders(params: QueryFolderParams = {}) {
    const res = await invokeIPC<BookmarkFolderDTO[]>(
      BOOKMARK_MANAGER_CHANNELS.QUERY_FOLDERS,
      params
    )
    if (res.success && res.data) {
      folders.value = res.data.sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0))
    }
    return res
  }

  // ==================== 书签操作 ====================

  async function addBookmark(input: {
    link: string
    title: string
    favicon?: string
    folder_id?: string | null
  }) {
    const res = await invokeIPC<BookmarkDTO>(BOOKMARK_MANAGER_CHANNELS.ADD_BOOKMARK, input)
    if (res.success) await loadBookmarks()
    return res.success
  }

  async function updateBookmark(input: {
    _id: string
    title?: string
    favicon?: string
    folder_id?: string | null
    sort?: number
  }) {
    const res = await invokeIPC<BookmarkDTO>(BOOKMARK_MANAGER_CHANNELS.UPDATE_BOOKMARK, input)
    if (res.success) await loadBookmarks()
    return res.success
  }

  async function deleteBookmark(_id: string) {
    const res = await invokeIPC<boolean>(BOOKMARK_MANAGER_CHANNELS.DELETE_BOOKMARK, _id)
    if (res.success) items.value = items.value.filter(b => b._id !== _id)
    return res.success
  }

  async function loadBookmarks(params: QueryBookmarkParams = {}) {
    isLoading.value = true
    try {
      const res = await invokeIPC<BookmarkDTO[]>(BOOKMARK_MANAGER_CHANNELS.QUERY_BOOKMARKS, params)
      if (res.success && res.data) {
        items.value = res.data.sort((a, b) => (a.sort ?? 0) - (b.sort ?? 0))
        total.value = res.count || Number(res.data.length)
      }
    } finally {
      isLoading.value = false
    }
  }

  // 导入
  async function importFromChrome(opts?: { filePath?: string; profile?: string }) {
    return await invokeIPC(BOOKMARK_MANAGER_CHANNELS.IMPORT_FROM_CHROME, opts)
  }

  async function importFromEdge(opts?: { filePath?: string; profile?: string }) {
    return await invokeIPC(BOOKMARK_MANAGER_CHANNELS.IMPORT_FROM_EDGE, opts)
  }

  // 同步
  async function syncToCloud() {
    const res = await invokeIPC<{ synced: number; failed: number }>(
      BOOKMARK_MANAGER_CHANNELS.SYNC_TO_CLOUD
    )
    return res.success
      ? { success: true, ...res.data }
      : { success: false, error: res.error || '同步失败' }
  }

  async function syncFromCloud(cloudBookmarks: F2.bookmark.Bookmark[]) {
    const res = await invokeIPC<{ imported: number; updated: number }>(
      BOOKMARK_MANAGER_CHANNELS.SYNC_FROM_CLOUD,
      cloudBookmarks
    )
    if (res.success) await loadBookmarks()
    return res.success
      ? { success: true, ...res.data }
      : { success: false, error: res.error || '同步失败' }
  }

  // 在文件夹内按新顺序重排（依次更新 sort）
  async function reorderInFolder(folder_id: string | null, orderedIds: string[]) {
    for (const [i, id] of orderedIds.entries()) {
      await updateBookmark({ _id: String(id), folder_id, sort: i })
    }
    await loadBookmarks()
  }

  return {
    items,
    folders,
    total,
    reorderInFolder,

    isLoading,
    settings,
    hasBookmarks,

    // 文件夹操作
    addFolder,
    updateFolder,
    deleteFolder,
    loadFolders,

    // 书签操作
    addBookmark,
    updateBookmark,
    deleteBookmark,
    loadBookmarks,
    importFromChrome,
    importFromEdge,
    syncToCloud,
    syncFromCloud
  }
})
